<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/*
 * yangzhic
 * 2016年8月17日下午6:50
 * OrderController
 */
namespace SDXApi\Controller;

use SDXApi\Service\OrderDistributionTimeService;
use Think\Controller;
use Think\Model;
use SDXApi\Service\UserBehavior;

class OrderController extends AppController {
	
	public function _initialize()
	{
		if(ACTION_NAME =='testfuck'){

			dump(get_included_files());
			parent::_initialize('','',false,'',true);

		}else{
			parent::_initialize('','',false,'',true);
		}

	}
	/*
	 * 订单删除
	 */
	public function myorder_del() {
		if (IS_POST) {
			$order_id = I ( 'post.order_id' );
			$uid = I ( 'post.uid' );
			if (empty ( $uid )) {
				returnApiError ( 'uid 不存在' );
			}
			if (empty ( $order_id )) {
				returnApiError ( 'order_id 不存在' );
			}
			
			$map = array (
					'order_id' => $order_id,
					'user_id' => $uid 
			);
			
			$order_info = D ( 'order_info' );
			$order_data = $order_info->where ( $map )->find ();
			
			if (empty ( $order_data )) {
				returnApiError ( '订单不存在' );
			}
			
			if ($order_data ['order_status'] != OS_CANCELED) {
				returnApiError ( '此订单不是取消状态，不可删除' );
			}
			$order_goods = D ( 'order_goods' );
			$order_action = D ( 'order_action' );
			
			// 删除订单信息
			$order_info->where ( $map )->delete ();
			// 删除订单中相关商品信息
			$order_goods->where ( $map )->delete ();
			// 删除订单操作日志
			$order_action->where ( $map )->delete ();
			
			$action_array = array (
					'delivery',
					'back' 
			);
			$res = $order_info->del_delivery ( $order_id, $action_array );
			
			if ($res) {
				returnApiSuccess ( array (), 'delete success.' );
			} else {
				returnApiError ( 'unknown request mode.' );
			}
		} else {
			returnApiError ( 'unknown request mode' );
		}
	}
	
	/**
	 * 保存准备发送短信的已确认订单
	 */
	public function insert_ready_sendmsg_order($order){
	    $data=array();
	    $data['order_id']=$order['order_id'];
	    $data['order_sn']=$order['order_sn'];
	    $data['consignee']=$order['consignee'];
	    $data['uid']=$order['user_id'];
	    $data['mobile_phone']=$order['mobile'];
	    $data['send_time']=gmtime()+7200;
	    $data['is_send']=0;
	    
	    M("order_confirm_sendmsg")->data($data)->add();
	}
	
	
	/*
	 * 订单确认收货
	 */
	public function myorder_confirm() {
	    //判断是否post请求
		if (IS_POST) {
			$order_id = I ( 'post.order_id' );
			$uid = I ( 'post.uid' );
            $runtime = S("user_confirm_order_".$order_id);
            if(!empty($runtime)){
                returnApiError('请勿重复点击');
            }else{
                S("user_confirm_order_".$order_id,"yes",20);
            }
			if (empty ( $uid )) {
				returnApiError ( 'uid 不存在' );
			}
			if (empty ( $order_id )) {
				returnApiError ( 'order_id 不存在' );
			}
			$map = array (
					'order_id' => $order_id,
					'user_id' => $uid,
			);
			
			$order_info = D ( 'order_info' );
			$order_data = $order_info->where ( $map )->find ();
			
			if (empty ( $order_data )) {
				returnApiError ( '订单不存在' );
			}
			
			if ($order_data ['shipping_status'] == SS_RECEIVED) {
				returnApiError ( '订单已收货' );
			} elseif ($order_data ['shipping_status'] != SS_SHIPPED&&$order_data ['shipping_status'] != 6) {
				returnApiError ( '订单还未发货' );
			} else { /* 修改订单发货状态为“确认收货” */
				$savedate = array (
						'shipping_status' => SS_RECEIVED ,
                        'confirm_time' => gmtime()
				);
				$map = array (
						'order_id' => $order_id,
						'user_id' => $uid, 
				);
				$res = $order_info->where ( $map )->save ( $savedate );
				if ($res !== false) {
					$order_data ['shipping_status'] = $savedate['shipping_status'];
					$order_action = D ( 'order_action' );
					$action_data = array ();
					$action_data ['order_id'] = $order_data ['order_id'];
					$action_data ['action_user'] = "buyer";
					$action_data ['order_status'] = $order_data ['order_status'];
					$action_data ['shipping_status'] = $order_data ['shipping_status'];
					$action_data ['pay_status'] = $order_data ['pay_status'];
					$action_data ['action_place'] = 0;
					$action_data ['action_note'] = "";
					$action_data ['log_time'] = gmtime ();
					//收货地址坐标
					$address = $this->get_address_gps($order_data['country'], $order_data['province'], $order_data['city'], $order_data['district'],$order_data['address']);
					$action_data ['longitude'] = $address['longitude'];
					$action_data ['latitude'] = $address['latitude'];
					//新增订单操作日志

					//收货确认减冻结库存
                    $is_shipping_status = M("order_action")->where(array("order_id"=>$order_id,"shipping_status"=>array("in",array(2,6))))->count();
                    if(empty($is_shipping_status)){
                        $this->order_buckle_inventory($order_data);
                        $action_data ['action_note'] = "扣减冻库";
                    }else{
                        $action_data ['action_note'] = "不操作库存";
                    }
                    $order_action->add ($action_data);
					//发送自提订单确认收货完成短信给收货人
					if($order_data['shipping_id'] == 2 && $order_data['referer'] != '门店'){
					    $wechat_param=array();
					    
					    switch($_SERVER['SERVER_NAME']){
					        case 'api.xian3.com':
					            $thisurl='xian3.com';
					            break;
					        case 'api.test.shidexian.com':
					            $thisurl='test.shidexian.com';
					            break;
					        case 'api.shidexian.com':
					            $thisurl='w.shidexian.com';
					            break;
					        default:
					            $thisurl='w.shidexian.com';
					            break;
					    }
					    $oid=$uid;
					    $Code=md5($uid.'sdx@9999');
					    
					    $wechat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$order_data['order_id']."&utm_source=GZHorder_finish_self";
					    $wechat_param['keyword1']=$order_data['order_sn'];
					    $wechat_param['keyword2']=sprintf("%.2f",($order_data['order_amount']+$order_data['money_paid']+$order_data['surplus']));
					    $wechat_param['keyword3']=date("Y-m-d H:i:s");
						$send_result = A("Smsapi")->send_message_api('order_finish_self',$order_data['mobile'],$order_data['consignee'],0,$order_data['order_sn'],0,$order_data['user_id'],array('amount'=>$order_data['goods_amount'],'time'=>local_date("Y-m-d H:i:s",$order_data['confirm_time'])),'',$wechat_param);
					}
					$this->insert_ready_sendmsg_order($order_data);
                    
                    //确认收货，赠送红包
                    D('Userbonus')->send_bonus_to_user($uid,$order_id);

                    //订单超时处理
                    $distribution = new OrderDistributionTimeService();
                    $distribution->add_order_info_overtime($order_id, 1);

					returnApiSuccess ( "", '确认收货成功' );
				} else {
					returnApiError ( '操作失败，请重试' );
				}
			}
		}else{
			returnApiError ( 'unknown request mode' );
		}
	}
	
	/*
	 * 收货确认减冻结库存
	 * */
	private  function order_buckle_inventory($order){
	    $wid=$order['wid'];
	    $order_goods=M('order_goods')->where(array('order_id'=>$order['order_id']))->select();
	    if($order_goods){
            $goodsstorage_mod=D('Goodsstorage');
            $goodsfreezerecord=D('Goodsfreezerecord');
            $refund_detail=M('refund_detail');
            $rdgoods=array();
            //检查退货退款时是否已经减掉了冻结库存，若有，该操作则不进行减操作
            $rdlist=$refund_detail->field('goods_id,SUM(refund_number) as refund_number')
                ->where(array('order_id'=>$order['order_id']))
                ->group('goods_id')
                ->select();
            if($rdlist){
                foreach ($rdlist as $key=>$val){
                    $rdgoods[$val['goods_id']]=$val['refund_number'];
                }
            }
            foreach ($order_goods as $k=>$v){
	             $gsdata=$goodsstorage_mod->get_warehous_goods($wid,$v['goods_id']);
	             if($gsdata){
                     if(!empty($rdgoods[$v['goods_id']])){
                         $refund_number=$rdgoods[$v['goods_id']];
                         $v['goods_number']=$v['goods_number']-ceil($refund_number);
                     }
                     if($v['goods_number']==0){
                         continue;
                     }
	                 //减去冻结库存
	                 $goodsstorage_mod->save_freeze_theactual_goods($wid,$v['goods_id'],$v['goods_number']);
	                 $goodsfreezerecorddata=array(
	                     'goods_storage_id'=>$gsdata['id'],
	                     'wid'=>$wid,
	                     'goods_id'=>$v['goods_id'],
	                     'goods_sn'=>$v['goods_sn'],
	                     'goods_name'=>$v['goods_name'],
	                     'freeze_num'=>$v['goods_number'],
	                     'real_num'=>0,
	                     'frozen_num'=>$gsdata['freeze_num']-$v['goods_number'],
	                     'defective_num'=>0,
	                     'operation_userid'=>0,
	                     'average_userid'=>$order['user_id'],
	                     'operation_addtime'=>gmtime(),
                         'source_no'=>$order['order_sn'],
	                     'record_type'=>6,
	                     'remark'=>'确认收货',
	                 );
	                 //生成冻结库存记录
	                 $goodsfreezerecord->add_freeze_record($goodsfreezerecorddata);
	             }else{
	                 continue;
	             }
	         }
	    }else{
	        return false;
	    }
	}

    /**
     * @param $country_id
     * @param $province_id
     * @param $city_id
     * @param $district_id
     * @param $address
     * @return mixed
     */
	public function get_address_gps($country_id,$province_id,$city_id,$district_id,$address){
		$country = M('region')->where(array('region_id'=>$country_id))->getField('region_name');
		$province = M('region')->where(array('region_id'=>$province_id))->getField('region_name');
		$city = M('region')->where(array('region_id'=>$city_id))->getField('region_name');
		$district = M('region')->where(array('region_id'=>$district_id))->getField('region_name');
		$all_address = str_replace(' ','',$country.$province.$city.$district.$address);
		$gps = address_to_gps_amap($all_address);
		return $gps;
	}

	public function get_distribution_time($inside_use_address_id =null,$in_day = false){
	    //todo 传入地址ID，自动匹配配送时间，后期不使用today
        if($in_day !== false){
            return D("Users")->distributie_time_list_new($in_day);
        }
        if($inside_use_address_id){
            //内部调用，不输出，只返回
            $get_fac = D('Useraddress')->check_serve_by_address_id($inside_use_address_id);
            //dump($get_fac);
            return D("Users")->distributie_time_list_new($get_fac['mode_id']);
        }else{

            $address_id = I ( 'post.address_id' );
            if(empty($address_id)){
                $address_id = I ( 'post.address_id_' );
            }

            if($address_id){
                $get_fac = D('Useraddress')->check_serve_by_address_id($address_id);

                $today = $get_fac['mode_id'];
            }else{
                $today = I ( 'post.today' );
                if($_POST['is_app']==1 && $_POST['version']<46){
                    $today = 10;
                }

            }
            if(empty($today)){
                //无地址 且无记录时 返回 空数据
                $Distribution_time['today'] = array(
                );
                $Distribution_time['tomorrow'] = array(
                );
            }else{
                $Distribution_time = D("Users")->distributie_time_list_new($today, $get_fac['wdr_id']);
            }
            //查询送货时间

            returnApiSuccess($Distribution_time,'Distribution_time');
        }

	}


    /**
     *订单申请退款
     */
    public function return_order(){
        $order_id = I ('post.order_id');  //所需退货的订单ID

        //查询订单是否已经收获确认且在24小时内

        $good_id_array = I ('post.good_id');            //退货商品ID组
        $good_num_array = I ('post.good_num');          //退货商品数量组
        $good_photo_array = I ('post.good_photo');      //退货商品图片组
        $good_des_array = I ('post.good_des');          //退货商品描述组

		D("Orderinfo")->submit_refund($order_id, $good_id_array, $good_num_array, $good_photo_array, $good_des_array);
	}

	/**
	 *获取订单退款状态
     */
	public function get_refund_state(){
		$order_id = I ('post.order_id');  //所需退货的订单ID
		D("Orderinfo")->refund_state($order_id);
	}
	
	public function get_order_again(){
		$uid = $this->uid;
		$order_id = I("post.order_id");
		
		$map = array('order_id'=>$order_id);
		$order_goods_list = M("order_goods")->where($map)->select();
		
		if(empty($order_goods_list)){
			returnApiError('没有商品');
		}
		
		//dump($order_goods_list);
		
	}

	public function order_cancel(){
		$uid = I ( 'post.uid' );
		$order_id = I('post.order_id');
		
		if (empty($uid) || empty($order_id)){
			returnApiError("参数不能为空");
		}
		$map = array();
		$map['user_id'] = $uid;
		$map['order_id'] = $order_id;
		$order_info = M("order_info")->where($map)->find();

		if(empty($order_info)){
			returnApiError("订单不存在");
		}
		
		if($order_info['order_status']==2){
			returnApiError("此订单已取消，请勿重复取消");
		}
        if($order_info['shipping_status']>0){
            returnApiError('订单正在发货中，不能取消，如需取消请联系客服处理');
        }

		if($order_info['order_status']==0 && $order_info['pay_status']==0){
			//未付款状态的自动取消订单


			if(in_array($order_info['wid'],C('K3_Wid')) ) {
				//金蝶取消订单
				$postToKingdee = $this->http_post(C("JD_HOST") . "/warehousemange/usershandordercancel", array("order_id" => $order_id, "user_id" => $uid));
				var_dump(array("order_id" => $order_id, "user_id" => $uid));

				$result = json_decode($postToKingdee, true);
				if ($result['code'] == 200) {
					returnApiSuccess('', "取消订单成功");
				} else {
					returnApiError("取消订单失败，请重试");
				}
			}else{
				$res = $this->order_cancel_by_id($order_info);

				if($res!==false){
					$where = array('order_id'=>$order_id);
					$order_goods = M("order_goods")->where($where)->select();
					foreach($order_goods as $item){
						if(is_numeric($item['goods_id'])){
							$this->check_goods_inventory($item['goods_id']);
						}
					}
					//写入取消订单操作记录
					$order_action_mod = D('OrderAction');
					$data = array(
						'order_id' => $order_info['order_id'],
						'action_user' => 'buyer',
						'order_status' => OS_CANCELED,
						'shipping_status' => $order_info['shipping_status'],
						'pay_status' => $order_info['pay_status'],
						'action_note' => '手动取消订单',
						'log_time' => gmtime()
					);
					$order_action_mod->insert_order_action($data);

					//写入行为日志
					$user_behavior = new UserBehavior();
					$user_behavior->add_user_behavior_order($uid, $order_id, 1, I('refund_note'));


					returnApiSuccess('', "取消订单成功");
				}else{
					returnApiError("取消订单失败，请重试");
				}
			}
		}elseif($order_info['order_status']>0 && $order_info['order_status']!=2&& $order_info['pay_status']!=4 && $order_info['pay_status']>1 && $order_info['shipping_status']==0){
		    //dump("dddd");
			//已付款未发货状态取消订单退款退货。
			//执行全单退款

			//金蝶取消订单
			$this->http_post("http://ts.shidexian.com/warehousemange/usershandordercancel", array("order_id"=>$order_id,"user_id"=>$uid));

			$url=C("SDX_SEND_DOMIANURL")."index.php?m=admin&c=Store&a=refund&api=skip";

			$back_goods_list = array(); //退货退款商品列表

			$goods_list= array();
			$sever_goods_list = $this->get_goods_list_real($order_id,true);
			//判断此有无提交数量超出实际商品剩余量的
			foreach ($sever_goods_list as $key2=>$value2){
                $goods_list['rec_id'] = $value2['rec_id'];
                $goods_list['act_id'] = $value2['act_id'];
				$goods_list['goods_id'] = $value2['goods_id'];
				if($value2['discount_price']>0){
                    $goods_list['goods_price'] = $value2['discount_price'];
                }else{
                    $goods_list['goods_price'] = $value2['goods_price'];
                }
				$goods_list['goods_name'] = urlencode($value2['goods_name']);;
				$goods_list['goods_sn'] = $value2['goods_sn'];
				$goods_list['cnt'] = $value2['real_num'];
				$goods_list['goods_number'] = $value2['real_num'];
				array_push($back_goods_list,$goods_list);
			}

			//执行退货退款操作
			if(count($back_goods_list)>0){
				$param['order_id'] = $order_id;
				$param['goods_list'] = json_encode($back_goods_list);
				$param['refund_type'] = '退货退款';
				$param['refund_amount'] = bcsub(bcadd(bcadd($order_info['money_paid'], $order_info['surplus'], 2), $order_info['order_amount'], 2), $order_info['refund_amount'], 2); //最大退款金额;
				$param['user_name'] = 'buyer';
				$param['admin_user'] = 'buyer';
				$param['is_recycling'] = '0';
				$param['refund_note'] = I('post.refund_note');
				$back_state = $this->rui_http_post($url,$param);
				if($back_state){
					//发送信息
					//A("Smsapi")->send_message_api("order_cancel_pickup",$order_info['mobile'],$order_info['consignee'],0,$order_info['order_sn'],0,$order_info['user_id'],array(),"");

                    //写入行为日志
                    $user_behavior = new UserBehavior();
                    $user_behavior->add_user_behavior_order($uid, $order_id, 1,  I('refund_note'));

                    $distribution = new OrderDistributionTimeService();
                    //添加当前区域的时间段订单量缓存 减一
                    if($order_info['shipping_id']==3 && $order_info['196_admin_id']==0){
                        $distribution->add_order_best_time_cache($order_info['wdr_id'], $order_info['best_time_start'], $order_info['best_time'], $order_info['order_id'], -1);
                    }


                    returnApiSuccess(null,"取消订单成功,您所支付的金额将原路退款");
				}else{
					returnApiError("取消订单失败，请重试");
				}
			}else{
				returnApiError("已结退款了");
			}
		}
	}


    /**
     * 取消未付款订单
     * @param $order_info
     * @return bool
     */
    private function order_cancel_by_id($order_info){

        $map = array('order_id'=>$order_info['order_id']);
        $order_data = array('order_status'=>2,'pay_note'=>'用户手动取消订单');
        $res = M('order_info')->where($map)->save($order_data);

        if($res!==false){
            if($order_info['pay_status']!=2){
                $order_goodslist = M('order_goods')->field('goods_id,goods_sn,goods_name,goods_number,is_presell,buckle_inventory')->where($map)->select();
                if($order_goodslist){
                    $goodsstorage_mod=D("Goodsstorage");
                    $goods_mod=M('goods');
                    foreach ($order_goodslist as $key=>$val){
                        $where=array('goods_id'=>$val['goods_id']);
                        $goods_number=$goods_mod->where($where)->getField('goods_number');
                        $goods_mod->where($where)->save(array('goods_number'=>$goods_number+$val['goods_number']));
                        if($val['is_presell']==0 || ($val['is_presell']==1 && $val['buckle_inventory']==1)){
                            $goodsstorage_list=$goodsstorage_mod->get_warehous_goods($order_info['wid'],$val['goods_id']);
                            //获取库存缓存
                            $cache_goods_practical_num = get_goods_practical_num_cache($val['goods_id'],$order_info['wid'],$goodsstorage_list['practical_num']);
                            //获取队列库存缓存
                            $cache_queue_goods_stock = get_queue_goods_stock($val['goods_id'],$order_info['wid']);
                            if($goodsstorage_list){
                                //核实实际库存出入库记录是否有商品下单记录-的操作，若有则返回true，否则返回false
                                $vgsr=$goodsstorage_mod->verify_gsr($order_info['wid'],$val['goods_id'],$order_info['order_sn']);
                                //核实冻结库存出入库记录是否有商品下单记录+的操作，若有则返回true，否则返回false
                                $vgfr=$goodsstorage_mod->verify_gfr($order_info['wid'],$val['goods_id'],$order_info['order_sn']);
                                $practical_num=$goodsstorage_list['practical_num']+$val['goods_number'];
                                $freeze_num=$goodsstorage_list['freeze_num']-$val['goods_number'];
                                $updata_gsdata=array();
                                if($vgsr){
                                    $updata_gsdata['practical_num']=$practical_num;
                                }
                                if($vgfr){
                                    $updata_gsdata['freeze_num']=$freeze_num;
                                }
                                if($vgsr || $vgfr){
                                    //总库存中 实际库存数+  冻结库存数-
                                    $flag = M('goods_storage')->where(array('goods_id'=>$val['goods_id'],'wid'=>$order_info['wid']))->save($updata_gsdata);
                                    unset($updata_gsdata);
                                    //更新库存缓存
                                    if($flag!==false){
                                        set_goods_practical_num_cache($val['goods_id'],$order_info['wid'],$cache_goods_practical_num+$val['goods_number']);
                                    }
                                }
                                if($vgsr){
                                    $goodsrecord=array(
                                        'goods_storage_id'=>$goodsstorage_list['id'],
                                        'wpid'=>0,
                                        'wid'=>$order_info['wid'],
                                        'goods_id'=>$val['goods_id'],
                                        'goods_sn'=>$val['goods_sn'],
                                        'operation_num'=>$val['goods_number'],
                                        'real_num'=>$practical_num,
                                        'frozen_num'=>0,
                                        'defective_num'=>0,
                                        'operation_userid'=>0,
                                        'average_userid'=>$order_info['user_id'],
                                        'operation_addtime'=>gmtime(),
                                        'source_no'=>$order_info['order_sn'],
                                        'record_type'=>6,
                                        'remark'=>'订单取消',
                                    );
                                    //商品出入库记录
                                    D('Goodsstoragerecord')->add_storage_record($goodsrecord);
                                    unset($goodsrecord);
                                    set_queue_goods_stock($val['goods_id'],$order_info['wid'],$cache_queue_goods_stock+$val['goods_number']);
                                }
                                if($vgfr){
                                    $goodsfreezerecord=array(
                                        'goods_storage_id'=>$goodsstorage_list['id'],
                                        'wid'=>$order_info['wid'],
                                        'goods_id'=>$val['goods_id'],
                                        'goods_sn'=>$val['goods_sn'],
                                        'goods_name'=>$val['goods_name'],
                                        'freeze_num'=>$val['goods_number'],
                                        'real_num'=>0,
                                        'frozen_num'=>$freeze_num,
                                        'defective_num'=>0,
                                        'operation_userid'=>0,
                                        'average_userid'=>$order_info['user_id'],
                                        'operation_addtime'=>gmtime(),
                                        'source_no'=>$order_info['order_sn'],
                                        'record_type'=>5,
                                        'remark'=>'订单取消',
                                    );
                                    //商品冻结出入记录
                                    D('Goodsfreezerecord')->add_freeze_record($goodsfreezerecord);
                                }
                            }
                        }
                    }
                }

                if($order_info['pay_status']==0 && $order_info['bonus_id']!=0){
                    $user_bouns_map = array('order_id'=>$order_info['order_id']);
                    $user_bouns_data = array('used_time'=>0,'order_id'=>0);
                    M('user_bonus')->where($user_bouns_map)->save($user_bouns_data);
                }

                if($order_info['pay_status']==0){
                    $order_info_data = array('to_buyer'=>'未支付手动取消订单','pay_note'=>'','money_paid'=>0,'order_amount'=>0,'surplus'=>0);
                    M('order_info')->where($map)->save($order_info_data);
                }

                M('activity_quota')->where($map)->delete();
                $where_o['order_id'] = $order_info['order_id'];
                if($order_info['pay_status']==0 && $order_info['bonus_freight_id']!=0){
                    $bonus_freight_array = M("order_info")->where($where_o)->getField("bonus_freight_id",true);
                    M("order_info")->where($where_o)->setField("bonus_freight_id",0);

                    $where_sq['bonus_id'] = array("in",$bonus_freight_array);

                    $data['used_time'] = 0;
                    $data['order_id'] = 0;
                    $data['pay_log_id'] = 0;

                    M("user_bonus")->where($where_sq)->save($data);
                }
            }
        }

        return $res;
    }


	/**
	 * 根据订单ID获取订单里面的原始商品（未退款之前的）
	 * @param $order_id
	 * @return mixed
	 */
	private function get_goods_list_by_order($order_id,$no_gift=false){
        if($no_gift){
            $where['order_id'] = $order_id;
            $where['giving'] = array("neq",1);
            return M("order_goods")->where($where)->select();
        }else{
            return M("order_goods")->where(array("order_id"=>$order_id))->select();
        }
	}

	/**
	 * 查询订单的退款商品记录
	 * @param $order_id
	 * @return mixed
	 */
    private function get_refund_goods_list($order_id){
        $refund_detail = M("refund_detail")->field("order_goods_id,sum(refund_number) as refund_number ,sum(surplus_number) as surplus_number,goods_id,goods_name,goods_sn ")->where(array("order_id"=>$order_id))->group('order_goods_id')->select();
        //dump(M("refund_detail")->getlastsql());
        return $refund_detail;
    }

	/**
	 * 获取订单内剩余商品数
	 * @param $order_id
	 * @return mixed
	 */
	public function get_goods_list_real($order_id,$no_gift =  false){
        $buy_goods_list = $this->get_goods_list_by_order($order_id,$no_gift);
        //dump($buy_goods_list);

        $refund_goods_list = $this->get_refund_goods_list($order_id);
        //dump($refund_goods_list);
//        exit();
        foreach ($buy_goods_list as $key=>$value){
            $buy_goods_list[$key]['cat_id'] = M("goods")->where(array("goods_id"=>$value['goods_id']))->getField('cat_id');
            $edit_goods = true;
            foreach ($refund_goods_list as $key2=>$value2){
                if($value['rec_id']==$value2['order_goods_id']){
                    $buy_goods_list[$key]['real_num'] = $value['goods_number']-$value2['refund_number'];
                    $edit_goods = false;
                }
            }
            if($edit_goods){
                $buy_goods_list[$key]['real_num'] = $value['goods_number'];
            }
            if($buy_goods_list[$key]['real_num']==0){
                unset($buy_goods_list[$key]);
            }
        }
        //dump($buy_goods_list);
        //echo "ddddddddd";
        //exit();
        return $buy_goods_list;
	}

	/**
	 * post 提交进行退款
	 * @param $url
	 * @param $param
	 */
	private function rui_http_post($url, $param){
		$post_file=false;
		$oCurl = curl_init();
		if(stripos($url,"https://")!==FALSE){
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
		}
		if (is_string($param) || $post_file) {
			$strPOST = $param;
		} else {
			$aPOST = array();
			foreach($param as $key=>$val){
				$aPOST[] = $key."=".urlencode($val);
			}
			$strPOST =  join("&", $aPOST);
		}
		curl_setopt($oCurl, CURLOPT_URL, $url);
		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($oCurl, CURLOPT_POST,true);
		curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
		$sContent = curl_exec($oCurl);
		$aStatus = curl_getinfo($oCurl);
		curl_close($oCurl);
		if(intval($aStatus["http_code"])==200){
			$res = json_decode($sContent,true);
			if($res['error']){
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
	}
	
	
	
	public function get_order_resttime(){
		$order_id = I('post.order_id');
		$user_id = I('post.uid');
		
		if(empty($order_id) || empty($user_id)){
			returnApiError("参数错误");
		}
		$where = array("order_id"=>$order_id,"user_id"=>$user_id);

        $data = M('order_info')->field('order_id,order_sn,add_time,order_amount,shipping_id,shipping_name')->where($where)->find();
        $add_time = $data['add_time'];
        $order_amount = $data['order_amount'];
//		$add_time  = M('order_info')->where($where)->getField("add_time");
//		$order_amount  = M('order_info')->where($where)->getField("order_amount");
		
		if(empty($data)){
			returnApiError("订单下单时间为空或订单不存在");
		}
		
		$userinfo = M('users')
		->where(array('user_id'=>$user_id))
		->find();
		//$data ['test']=$userinfo;
		//        用户余额
		$amount = $userinfo ['user_money'] + $userinfo ['credit_line'];
		if(floatval($amount-$order_amount)<0){
		    $data ['payment']='0';
		}else{
		    $data ['payment']='1';
		}
		
		$data ['need_pwd']='0';
		if($amount>=$order_amount || $amount>50 && $amount<$order_amount){
		    $data ['need_pwd']='1';
		}
		
		
		$rest_pay_time = REST_PAY_TIME-(gmtime()-$add_time);
		$data ['rest_time'] = $rest_pay_time<0?0:$rest_pay_time;;
		returnApiSuccess($data);
	}
	
	public function http_post($url, $param, $post_file = false) {
	    $oCurl = curl_init();
	    if (stripos($url, "https://") !== FALSE) {
	        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
	        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
	        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
	    }
	    if (is_string($param) || $post_file) {
	        $strPOST = $param;
	    } else {
	        $aPOST = array();
	        foreach ($param as $key => $val) {
	            $aPOST[] = $key . "=" . urlencode($val);
	        }
	        $strPOST = join("&", $aPOST);
	    }
	    curl_setopt($oCurl, CURLOPT_URL, $url);
	    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($oCurl, CURLOPT_POST, true);
	    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
	    $sContent = curl_exec($oCurl);
	    $aStatus = curl_getinfo($oCurl);
	    curl_close($oCurl);
	    if (intval($aStatus["http_code"]) == 200) {
	        return $sContent;
	    } else {
	        return false;
	    }
	}
	
	/**
	 * 到货通知检测
	 * @param unknown $goods_id
	 */
	public function check_goods_inventory($goods_id){

        $Model = M();
	    $sql = 'SELECT bg.rec_id,bg.link_man, bg.goods_id,bg.booking_time,bg.tel,bg.user_id,bg.wid ' .'FROM ' .C('DB_PREFIX').'booking_goods AS bg ' ."WHERE bg.goods_id = ".$goods_id." and bg.is_send_m='0' and bg.booking_time>".(gmtime()-(3*24*60*60));
	    $booking_info_list = $Model->query($sql);
	    
	    foreach($booking_info_list as $booking_info){
	        $sql = 'SELECT g.goods_number,g.goods_name ' .'FROM ' .C('DB_PREFIX'). 'goods AS g ' ."WHERE g.is_presell='1' and g.goods_id =".$goods_id;
	        $goods_inventory1 = $Model->query($sql);
	        
	        $sql = 'SELECT gs.practical_num,gs.goods_name ' .'FROM ' .C('DB_PREFIX'). 'goods_storage AS gs ' ."WHERE gs.wid = ".$booking_info['wid']." and gs.goods_id =".$goods_id;
	        $goods_inventory2 = $Model->query($sql);
	        
	        if($goods_inventory1[0]['goods_number']+$goods_inventory2[0]['practical_num']-C("rest_goods_number")>=3){
	            $goods_inventory=$goods_inventory1[0];
	            $goods_name=$goods_inventory['goods_name'];
	            if(empty($goods_name)){
	                $goods_name=$goods_inventory2[0]['goods_name'];
	            }
	            /*短信通知处理*/
	            /* $remark["goods_name"]=$booking_info['goods_name'];
	             A("Smsapi")->send_message_api('goods_arrive_favorite',$booking_info['tel'],$booking_info['link_man'],0,0,0,$booking_info['user_id'],$remark); */
	
	            //发送短信
	
	            $thisurl=$_SERVER['SERVER_NAME'];
	
	            $url = "http://".$thisurl . "/index.php?m=default&c=Smsapi&a=send_message_url";
	            
	            $user_name='食得鲜会员';
	            $sql = 'SELECT consignee ' .'FROM ' .C('DB_PREFIX'). 'order_info ' ."WHERE user_id =".$booking_info['user_id'];
	            $rs = $Model->query($sql);
	            $get_consignee=$rs[0]["consignee"];
	            if(!empty($get_consignee)){
	                $user_name=$get_consignee;
	            }
	            $wechat_param=array();
	            switch($_SERVER['SERVER_NAME']){
	                case 'api.xian3.com':
	                    $thisurl='xian3.com';
	                    break;
	                case 'api.test.shidexian.com':
	                    $thisurl='test.shidexian.com';
	                    break;
	                case 'api.shidexian.com':
	                    $thisurl='w.shidexian.com';
	                    break;
	                default:
	                    $thisurl='w.shidexian.com';
	                    break;
	            }
	            $oid=$booking_info['user_id'];
	            $Code=md5($booking_info['user_id'].'sdx@9999');
	             
	            $wechat_param['url']="https://".$thisurl."/?index=/info?id=".$booking_info['goods_id']."&utm_source=GZHgoods_arrive_favorite";
	            $wechat_param['keyword1']=$goods_name;
	            $wechat_param['keyword2']=1;
	            
	            $data=array();
	            $data['wechat_param'] = $wechat_param;
	            $data['message_code'] = 'goods_arrive_favorite';
	            $data['user_phone'] = $booking_info['tel'];
	            $data['user_name'] = $user_name;
	            $data['user_rank'] = 0;
	            $data['order_sn'] = 0;
	            $data['ver_code'] = 0;
	            $data['user_id'] = $booking_info['user_id'];
	            $data['remark'] = array('goods_name'=>$goods_name);
	            $post['data'] = json_encode($data);
	            $state=$this->http_post($url, $post);
	            $res=json_decode($state);
	            
	            if($res->state==1){
	
	                
	                $sql = "UPDATE  ".C('DB_PREFIX')."booking_goods SET is_send_m='1',send_m_time=".gmtime()." WHERE rec_id='".$booking_info['rec_id']."'";
	                $Model->execute($sql);
	                
	                /*自动加入我的收藏*/
	                // 检查是否已经存在于用户的收藏夹
	                $where['user_id'] = $booking_info['user_id'];
	                $where['goods_id'] = $booking_info['goods_id'];
	                $sql ="SELECT count(rec_id) as count FROM " . C('DB_PREFIX')."collect_goods WHERE user_id ='".$booking_info['user_id']."' and goods_id='".$booking_info['goods_id']."'";
	                //$rs=$GLOBALS['db']->GetRow($sql);
	                $rs=$Model->query($sql);
	                
	                //$rs = $this->model->table('collect_goods')->where($where)->count();
	                if ($rs[0]['count'] == 0) {
	
	                    $data="user_id='".$booking_info['user_id']."'";
	                    $data.=",goods_id='".$booking_info['goods_id']."'";
	                    $data.=",add_time='".gmtime()."'";
	
	                    $sql = "insert into ".C('DB_PREFIX')."collect_goods SET $data";
	                    $state=$Model->execute($sql);
	                    
	
	                }
	                
	                
	                
	            }
	        }
	    }
	    
	}

    /**
     * 检查修正订单所在区域
     * 用于修改地标后手动纠正订单的配送区域信息
     */
    public function check_order_area(){
        $order_id = I('get.order_id');
        header("Content-type: text/html; charset=utf-8");
        if(is_numeric($order_id)){
            $order_info = M("order_info")->field("province,city,district,address,sign_building,longitude,latitude")->where(array("order_id"=>$order_id))->find();
            if(!empty($order_info)){
                $landmark = M("landmark_repair")->where(array("name"=>$order_info['sign_building'],"district_id"=>$order_info['district']))->field("lat,lng")->find();
                //dump($landmark);
                if(!empty($landmark)&&$landmark['lat']!=$order_info['latitude']&&$landmark['lng']!=$order_info['longitude']){
                    //此地标已变动，修改订单内的配送信息
                    //$landmark['lat'],$landmark['lng'];
                }else{
                    $province = M('region')->where('region_id ='.$order_info['province'])->getField('region_name');
                    $city = M('region')->where('region_id ='.$order_info['city'])->getField('region_name');
                    $district = M('region')->where('region_id ='.$order_info['district'])->getField('region_name');
                    $all_address = $province.$city.$district.$order_info['sign_building'];
                    $address_gps = address_to_gps_amap($all_address,$city);
//                    dump($address_gps);
//                    dump($all_address);
                    $landmark['lat'] = $address_gps['longitude'];
                    $landmark['lng'] = $address_gps['latitude'];
                }
                $arr = D('Users')->get_distribution_by_gps($landmark['lat'],$landmark['lng']);

                if($arr){
                    if($arr['wdr_id']>0){
                        $data['wdr_id'] = $arr['wdr_id'];
                        $data['longitude'] = $landmark['lng'];
                        $data['latitude'] = $landmark['lat'];
                        M("order_info")->where(array("order_id"=>$order_id))->save($data);
                        exit("1,".M("warehouse_deliver_region")->where(array("id"=>$arr['wdr_id']))->getField("name"));
                    }else{
                        //已超出配送区域
                        exit("0,已超出配送区域");
                    }
                }
            }else{
                //无此订单
                exit("0,无此订单");
            }

        }else{
            //订单ID错误
            exit("0,订单ID错误");
        }
    }

    public function get_order_share_info(){
        $res = C('BONUS_SHARE_INFO');
        returnApiSuccess($res);
    }
}